package com.mar.framecompress;

import java.nio.ByteBuffer;
import java.nio.IntBuffer;

public class FrameDecoder {
	private static final int DEFAULT_BUFF_SIZE = 1024;

	private final IDecoder dataDecoder;
	private final IColorDecoder colorDecoder;
	private final PixelFormat pixelFormat;
	private final ByteBuffer tmpBuffer;
	
	public FrameDecoder(IDecoder dataDecoder, IColorDecoder colorDecoder, PixelFormat pixelFormat) {
		if ( pixelFormat.bpp != 8 ){
			throw new IllegalArgumentException("Only 8 bit per pixel is format is supported in this implementation!");
		}
		this.pixelFormat = pixelFormat;
		this.dataDecoder = dataDecoder;
		this.colorDecoder = colorDecoder;
		this.tmpBuffer = ByteBuffer.allocate(DEFAULT_BUFF_SIZE);
	}
	
	public Frame decode(int x, int y, int width, int height, ByteBuffer encodedData){
		Frame frame = new Frame();
		frame.setX(x);
		frame.setY(y);
		frame.setWidth(width);
		frame.setHeight(height);
		
		dataDecoder.decode(encodedData, tmpBuffer);
		tmpBuffer.flip();
		
		IntBuffer argbBuffer = frame.getArgbBuffer();
		while ( tmpBuffer.hasRemaining() ){
			argbBuffer.put( colorDecoder.decode(  tmpBuffer.get(), pixelFormat.bpp ) );
		}
		
		tmpBuffer.flip();
		argbBuffer.flip();
		
		return frame;
	}
}
